<?php
/**
 * Created by PhpStorm.
 * User: alei
 * Date: 11/4/2017 AD
 * Time: 16:17
 */
namespace App\Http\Controllers\MobileApi;

use Storage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Mysql\pre_ct_ui;
use App\Models\Mysql\table_n;
use App\Models\Mysql\pre_forum_thread;
use App\Models\Mysql\pre_ct_draft;
use App\Models\Mysql\pre_ct_translatedtext;
use App\Models\Mysql\pre_forum_post;

class HomeController extends Controller
{
	use GlobalData;

	const ROUTE_PREFIX = '/api/*';

	protected $request;

	protected static $forumNameMapFID;

	protected $curTime;

	protected static $threadListConf = [
		1 => [
			'ch' => '翻译中', 'en' => 'in_translate'
		],
		2 => [
			'ch' => '点评中', 'en' => 'in_comment'
		],
		3 => [
			'ch' => '优秀译文', 'en' => 'translated_text'
		]
	];

	protected static $difficulty = ['低级','中级','高级'];

	protected static $menuBelowSwipers = [
		'bili_reading' => '双语阅读',
		'top_list' =>'排行榜',
		'online_dic' => '在线词典',
		'about_me' => '关于我们'
	];

	protected static $homeBellowMenu = [
		'home' => '首页',
		'task' => '任务',
		'translated_text' => '译文',
		'my' => '我的'
	];

	/**
	 * 创建新的home控制器实例
	 * @param \Illuminate\Http\Request $request
	 */
	public function __construct(Request $request)
	{
		$this->request = $request;
		$this->error = [];
		$this->curTime = time();

		self::$forumNameMapFID = $this->getForumNameMapFID();

		if(config('app.debug')) {
			error_reporting(E_ALL | E_STRICT);
		}
	}

	/**
	 * API：首页接口
	 *
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function GetPortalInfo()
	{
		try {
			if(! $this->check($this->request)) return responseJson($this->getError());
			$data = [
				'swipers' => [],
				'menuBelowSwipers' => [],
				'translationTime' => [],
				'translationTimeEmptyPicUrl' => '',
				'votingTime' => [],
				'votingTimeEmptyPicUrl' => '',
				'outstandingTranslation' => [],
				'outstandingTranslationHref' => '',
				'outstandingTranslationEmptyPicUrl' => '',
				'classicsAppreciation' => [],
				'classicsAppreciationHref' => '',
				'xianerStory' => [],
				'menuAtBottom' => []
			];
			$input = ['uid' => $this->request->uid];

			//1.获取首页轮播图及相关内容`swipers`
			$tmp = $this->selectPreCtUi();
			if(! empty($tmp)) {
				foreach ($tmp as $k => $v) {
					$data['swipers'][$k] = [];
					$data['swipers'][$k]['coverUrl'] = config('applqyw.discuz_server_url').$v->cover;
					$data['swipers'][$k]['title'] = $v->subject;
					$data['swipers'][$k]['href'] = '/api/forum?mod=viewthread&tid='.$v->tid;
					$data['swipers'][$k]['tid'] = $v->tid;
				}
			}
			$tmp = $k = $v = null;
			//2.`menuBelowSwipers`轮播图下方的菜单
			foreach(self::$menuBelowSwipers as $k => $v) {
				$data['menuBelowSwipers'][$k]['title'] = $v;
				$data['menuBelowSwipers'][$k]['picUrl'] = ''; //TODO
				$data['menuBelowSwipers'][$k]['href'] = self::getMenuHref($k, $this->request);
			}

			//3.`translationTime`正在翻译中的任务
			//4.`translationTimeEmptyPicUrl`
			//  如果translationTime为空，在那个区域会显示一张图片，本字段是这张图片的URL
			//5.`votingTime`正在点评中的任务
			//6.`votingTimeEmptyPicUrl`如果votingTime为空，在那个区域会显示一张图片，本字段是这张图片的URL
			$tmp = $this->selectHomeGoodAndCommentArticle($input);
			foreach([
						'in_translate' => 'translationTime',
						'in_comment'   => 'votingTime'
					] as $myf => $f) {
				if($tmp && isset($tmp[$myf]) && ! empty($tmp[$myf])) {
					foreach($tmp[$myf] as $k => $v) {
						$data[$f][$k] = [];
						$data[$f][$k]['subject'] = $v->series_subject;
						$data[$f][$k]['body'] = $v->message;
						$data[$f][$k]['difficulty'] = $v->difficulty;
						$data[$f][$k]['alreadySubmitCount'] = $v->trans_count;
						$data[$f][$k]['maxSubmitCount'] = $v->maxsubmitnumber;
						$data[$f][$k]['daysCountDown'] = $v->remaintime[0];
						$data[$f][$k]['hoursCountDown'] = $v->remaintime[1];
						$data[$f][$k]['minutesCountDown'] = $v->remaintime[2];
						$data[$f][$k]['iWantStatus'] = $v->ct_my_status;
						$data[$f][$k]['iWantHref'] = $this->makeIWantHref($v);
						$data[$f][$k]['tid'] = $v->tid;
					}
				} else {
					if('translationTime' === $f)
						$data['translationTimeEmptyPicUrl'] = self::getEmptyPicUrl('translationTimeEmptyPicUrl');
					elseif('votingTime' === $f)
						$data['votingTimeEmptyPicUrl'] = self::getEmptyPicUrl('votingTimeEmptyPicUrl');
				}
			}
			$k = $v = $myf = $f = null;

			//7.`outstandingTranslation`优秀译文
			//8.`outstandingTranslationHref`点击“>”跳转到的链接（优秀译文页面的链接）
			//9.`outstandingTranslationEmptyPicUrl`
			//  如果outstandingTranslation为空，在那个区域会显示一张图片，本字段是这张图片的URL
			if($tmp && isset($tmp['translated_text']) && !empty($tmp['translated_text'])) {
				foreach($tmp['translated_text'] as $k => $v) {
					$data['outstandingTranslation'][$k] = [];
					$data['outstandingTranslation'][$k]['authorAvatarUrl'] = avatarUrl($v->authorid);
						/*self::get_uc_server_image_url(
							$this->request->uid,
							$this->request->size,
							$this->request->type,
							$this->request->random,
							$this->request->check_file_exists);*/
					$data['outstandingTranslation'][$k]['authorName'] = $v->author;
					$data['outstandingTranslation'][$k]['subject'] = $v->series_subject;
					$data['outstandingTranslation'][$k]['body'] = $v->message;
					$data['outstandingTranslation'][$k]['replyCount'] = $v->replies;
					$data['outstandingTranslation'][$k]['voteCredits'] = $v->weightedvotes;
					$data['outstandingTranslation'][$k]['tid'] = $v->tid;
					//TODO
//					$data['outstandingTranslation'][$k]['outstandingTranslationHref'] = ;
				}
			} else {
				$data['outstandingTranslationEmptyPicUrl'] =
					self::getEmptyPicUrl('outstandingTranslationEmptyPicUrl');
			}

			$tmp = $k = $v= null;
			//10.`classicsAppreciation`经典赏析
			//11.`classicsAppreciationHref`点击“>”跳转到的链接（经典赏析页面的链接）
			$tmp = $this->selectClassicsAppreciation();
			if(! empty($tmp)) {
				foreach($tmp as $k => $v) {
					$data['classicsAppreciation'][$k] = [];
					$data['classicsAppreciation'][$k]['coverUrl'] = config('applqyw.discuz_server_url').$v->cover;
					$data['classicsAppreciation'][$k]['subject'] = $v->subject;
/*					
	$classics_appreciation['message'] = str_replace("[//]", '', strip_tags($classics_appreciation['message']));
	$classics_appreciation['message'] = messagecutstr($classics_appreciation['message'], $show_msg_len);
	$classics_appreciation['message'] = discuzcode($classics_appreciation['message'], 0, 0, 0, 1, 1, 0, 0, 0, 0, 0);
	$classics_appreciation['message'] = str_replace(array("\r", "\n",), '', $classics_appreciation['message']);					*/
					$tmp_message = $v->message;
					$tmp_message = strip_tags($tmp_message);
					$tmp_message = messagecutstr($tmp_message);
					$data['classicsAppreciation'][$k]['body'] = $tmp_message;
					
					//各个主题href
					$data['classicsAppreciation'][$k]['href'] = '/api/forum?mod=viewthread&tid='.$v->tid;
					$data['classicsAppreciation'][$k]['tid'] = $v->tid;
				}
				//更多" > " href
				$data['classicsAppreciationHref']
					= 'api/forum?mod=forumdisplay&fid='.self::$forumNameMapFID['jdsy_classicsappreciation'];
			}
//			else {
//				$data['classicsAppreciationEmptyPicUrl'] = self::getEmptyPicUrl('classicsAppreciationEmptyPicUrl');
//			}

			$tmp = $k = $v = null;
			//12.`xianerStory`贤二漫画
			$tmp = $this->selectXianercartoon();
			if($tmp) {
				$data['xianerStory']['coverUrl'] = config('applqyw.discuz_server_url').$tmp->cover;
				$data['xianerStory']['href'] = 'api/forum?mod=viewthread&tid='.$tmp->tid;
				$data['xianerStory']['tid'] = $tmp->tid;
			}
			//13.`menuAtBottom`底部菜单，4个菜单项，每个菜单项是一个图片按钮
			foreach(self::$homeBellowMenu as $k => $v) {
				$data['menuAtBottom'][$k]['picUrl'] = ''; //TODO
				$data['menuAtBottom'][$k]['title'] = $v;
				$data['menuAtBottom'][$k]['href'] = self::getMenuHref($k, $this->request);
			}

			return responseJson('success', $data, TRUE);

		} catch (\Exception $e) {
			return responseJson($e->getFile().': '.$e->getLine().': '.$e->getMessage());
		}
	}

	/**
	 * 获取：点击“我要翻译”（或者我的译文、我的草稿、友情翻译）之后跳转之页面的接口路由
	 * @param $d
	 * @return string
	 */
	protected function makeIWantHref(&$d)
	{
//		$forumNameMapFID = $this->getForumNameMapFID();

		$prefix_1 = '/api/forum?mod=post&action=newthread';
		$prefix_2 = '/api/forum?mod=post&action=edit';

		if(! isset($d->ct_my_status)) return '';
		switch($d->ct_my_status) {
			case 0 : //我要翻译
			case 1 : //我的草稿
			case 3 : //友情翻译
				return $prefix_1.'&fid='. self::$forumNameMapFID['fxzy_translating']
				.'&cttaskid='.$d->taskid;
			case 2 : //我的译文
				return $prefix_2.'&fid='.self::$forumNameMapFID['fxzy_translating']
				.'&tid='.$d->ct_my_tran_tid.'&pid='.$d->ct_my_tran_pid;
		}
		return '';
	}

	/**
	 * API：获取首页轮播图及相关内容
	 * !!!注意：凡是路由请求的方法第一个字母大写，且为public属性，下同
	 *
	 * @param \Illuminate\Http\Request $request
	 */
	public function GetHomeRollPicture()
	{
		try {
			if(! $this->check($this->request)) return responseJson($this->getError());
			return responseJson('success', $this->selectPreCtUi(), TRUE);
		} catch (\Exception $e) {
//			return responseJson($e->getMessage());
			return responseJson($e->getFile().': '.$e->getLine().': '.$e->getMessage());
		}
	}

	/**
	 * 查询图片url及相关内容等数据
	 * @return mixed
	 */
	protected function selectPreCtUi()
	{
		//也可以使用ORM，底层也是用查询构造器，只不过laravel做了很多封装，封装了对象关系模型
		//但是要使用原生sql查询，还是需用查询构造器方法
//		$result = pre_ct_ui::select('*')
//			->where('subcategory','swiper')
//			->where('category','portal')
//			->get()->toArray();
		//使用laravel的数据库查询构造器方法
		$result = pre_ct_ui::getRollPictureData();
		$index = 0; $thisObj = $this;
		array_walk($result, function(&$item, $i) use(&$index, &$thisObj) {
			$item->index = $index;
			if (! empty(trim($item->extra1))) {
				$item->cover = trim($item->extra1);
			} else {
				$item->cover = $thisObj->get_pic_url_by_pid($item->tid, $item->pid);
			}
			++$index;
		});
		return $result;
	}

	public function get_pic_url_by_pid($tid, $pid)
	{
		$temp = app(table_n::class)->fetch_all_by_id('tid:'.$tid, 'pid', array($pid), '', TRUE);
		$retval = '';
		foreach($temp as $attach){
			$retval = $attach->remote
					? Storage::disk('ftp')->url($attach->attachment)
					: Storage::disk('local')->url($attach->attachment);
			if($retval) break;
		}
		return $retval;
	}

	/**
	 * API: 获取首页【翻译中，点评中，优秀译文】板块的内容
	 *
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function GetHomeGoodAndCommentArticle()
	{
		try {
			if(! $this->check($this->request)) return responseJson($this->getError());
			$input = ['uid' => $this->request->uid];
			return responseJson('success', $this->selectHomeGoodAndCommentArticle($input), TRUE);
		} catch (\Exception $e) {
			return responseJson($e->getFile().': '.$e->getLine().': '.$e->getMessage());
		}
	}

	/**
	 * 查询并组合首页【翻译中，点评中，优秀译文】板块的内容
	 *
	 * @param $input
	 * @return array
	 */
	protected function selectHomeGoodAndCommentArticle(&$input)
	{
		$thisObj = $this;
		$threadlist = [];
		array_walk(self::$threadListConf, function(&$item, &$i) use(&$thisObj, &$input, &$threadlist) {
			$whichtid = ($i<3) ? 'srctid' : 'besttid';
			$whichorder = ($i==1) ? 'publishtime' : (($i==2) ? 'submittime' : 'commentendtime');
			$threadlistData = pre_forum_thread::selectHomeThreadList([
				'whichtid' => $whichtid,
				'whichorder' => $whichorder,
				'ct_task_status' => $i
			]);
			$threadindex = 0;
			$threadlist[$item['en']] = [];
//			dd($threadlistData);
			array_walk($threadlistData, function(&$thread) use(&$threadindex,
				&$thisObj, &$i, &$input, &$threadlist, &$item) {
				$thread->html_index = $threadindex + 1;
				$thread->series_subject = '['.trim($thread->seriesname).']'.$thread->subject;
				$thread->difficulty = self::$difficulty[$thread->difficulty];

				if ($i==1) {
					$thread->remaintime = remain_time($thread->submittime - $thisObj->curTime);
				} elseif($i==2) {
					$thread->remaintime = remain_time($thread->commentendtime - $thisObj->curTime);
				}

				//0:未提交译文，1：草稿，2：已经提交译文，3：已经到达提交人数了（仅对翻译中有效）
				$ct_my_status=0;
				if ($i==1) {
					if($input['uid']) {
						$draft = pre_ct_draft::getDraftBlongUidTaskID([
							'uid' => $input['uid'],
							'taskid' => $thread->taskid
						]);
						if(! empty($draft)) {
							$ct_my_status = 1;
						} else {
							$ct_my_tran_tid = pre_ct_translatedtext::first_tid_translatedtext([
								'uid' => $input['uid'],
								'taskid' => $thread->taskid
							]);
							if (! empty($ct_my_tran_tid)) {
								$ct_my_status = 2;
								//假设帖子不分表
								$ct_my_tran_pid = pre_forum_post::first_pid_forum_post([
									'tid' => $ct_my_tran_tid
								]);
								$thread->ct_my_tran_tid = $ct_my_tran_tid;
								$thread->ct_my_tran_pid = $ct_my_tran_pid;
							}
						}
					}
				}
				$trans_count = pre_ct_translatedtext::count_tid(['taskid'=>$thread->taskid]);
				$thread->trans_count = $trans_count;
				if (($trans_count >= $thread->maxsubmitnumber)
					&& ($ct_my_status <> 1) && ($ct_my_status <> 2)){
					$ct_my_status=3;
				}
				$thread->ct_my_status = $ct_my_status;

				if($i == 3) {
					$thread->weightedvotes = pre_ct_translatedtext::first_weightedvotes([
						'tid' => $thread->tid
					]);
				}

				$t_post = pre_forum_post::fetch_first([
					'field' => 'pid,message',
					'tid' => $thread->tid
				]);
//				$show_msg_len = ($i < 3) ? 150 : 60;
//				$t_post->message = str_replace("[//]", '', strip_tags($t_post->message));
//				$t_post->message = messagecutstr($t_post->message, $show_msg_len);
//				$t_post->message = discuzcode($t_post->message, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0);
//				$thread->message = str_replace(array("\r", "\n",), '', $t_post->message);
				$tmp_message = $t_post->message;
				$tmp_message = str_replace("[//]", ' ', strip_tags($tmp_message));
				$tmp_message = messagecutstr($tmp_message);
				$thread->message = $tmp_message;
				$thread->pid = $t_post->pid; //见pc网站：added by lqyw lishu 20170902

				$threadlist[$item['en']][$threadindex]=$thread;
				$threadindex++;
			});
		});
		return $threadlist;
	}

	/*-----------------------------首页经典赏析接口----------------------------*/
	/**
	 * API：获取首页【经典赏析】模块的内容
	 *
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function GetClassicsAppreciation()
	{
		try {
			if(! $this->check($this->request)) return responseJson($this->getError());
			return responseJson('success', $this->selectClassicsAppreciation(), TRUE);
		} catch (\Exception $e) {
			return responseJson($e->getFile().': '.$e->getLine().': '.$e->getMessage());
		}
	}

	/**
	 * 服务于：获取首页【经典赏析】模块的内容
	 *
	 * @return mixed
	 */
	protected function selectClassicsAppreciation()
	{
		$classicsAppreciation = pre_forum_thread::selectClassicsAppreciation([
			'category' => 'portal',
			'subcategory' => 'classicsappreciation'
		]);
		$htmlIndex = 0; $thisObj = $this;
		array_walk($classicsAppreciation, function(&$item) use(&$htmlIndex, &$thisObj) {
			$item->htmlIndex = $htmlIndex + 3;
			if(! empty($temp = trim($item->extra1))) {
				$item->cover = $temp;
			} else {
				$item->cover = $thisObj->get_pic_url_by_pid($item->tid, $item->pid);
			}
			++$htmlIndex;
		});
		return $classicsAppreciation;
	}

	/*-------------------------API: 获取首页【贤二漫画】板块内容--------------------*/
	/**
	 * API: 获取首页【贤二漫画】板块内容
	 *
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function GetXianercartoon()
	{
		try {
			if(! $this->check($this->request)) return responseJson($this->getError());
			return responseJson('success', $this->selectXianercartoon(), TRUE);
		} catch (\Exception $e) {
			return responseJson($e->getFile().': '.$e->getLine().': '.$e->getMessage());
		}
	}

	protected function selectXianercartoon()
	{
		$xianercartoon = pre_ct_ui::selectXianercartoon([
			'category' => 'portal',
			'subcategory' => 'xianercartoon'
		]);
		if($xianercartoon && isset($xianercartoon[0])) {
			$xianercartoon = $xianercartoon[0];
			if(empty($xianercartoon->extra1)) {
				$xianercartoon->cover = $this->get_pic_url_by_pid($xianercartoon->tid, $xianercartoon->pid);
			} else {
				$xianercartoon->cover = $xianercartoon->extra1;
			}
			return $xianercartoon;
		}
		return [];
	}

	public  function  ce()
    {
        $data = pre_ct_ui::get_ce();
        $data=json_decode(json_encode($data),true);
        echo '<pre>';
        print_r($data) ;

    }























} //!end HomeController
